package com.heima.wemedia.service.impl;



import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmNewsPageReqDto;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {




    @Override
    public ResponseResult findlist(WmNewsPageReqDto wmNewsPageReqDto) {
        //检查参数
        // 分页检查
        wmNewsPageReqDto.checkParam();
        // 分页条件查询
        IPage page=new Page(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize());
        //构建mybatisplus查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        // 状态精确查询
        if (wmNewsPageReqDto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus,wmNewsPageReqDto.getStatus());
        }
        // 频道查询
        if (wmNewsPageReqDto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId,wmNewsPageReqDto.getChannelId());
        }
        // 时间范围查询
        if (wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null) {
            //条件一  查询条件 23  查询条件介于左右之间，
            lambdaQueryWrapper.between(WmNews::getPublishTime,wmNewsPageReqDto.getBeginPubDate(),wmNewsPageReqDto.getEndPubDate());
        }
        // 关键字的模糊查询
        if (StringUtils.isNotBlank(wmNewsPageReqDto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle,wmNewsPageReqDto.getKeyword());
        }
        //根据当前登录人查询
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        //按照发布时间倒叙查询
            lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);
        page= page(page,lambdaQueryWrapper);
        // 结果返回
        ResponseResult responseResult = new PageResponseResult(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //条件判断
        if (dto==null || dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存or修改文章
        WmNews wmNews=new WmNews();
        //属性拷贝
        BeanUtils.copyProperties(dto,wmNews);
        //封面图片
        if (dto.getImages()!=null && dto.getImages().size()>0){
            String imagestr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imagestr);
        }
        //封面为类型为自动 -1
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);
        // 判断是否草稿  是草稿的话
        if (wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);

        }
        // 不是草稿 保存文章内容图片和素材内容
        //获取文章内容图片信息
        List<String>materials=ectractUrlInfo(dto.getContent());
        saveRelativeInfoForCONTENT(materials,wmNews.getId());
        // 不是草稿 ，保存文章封面和素材有关的内容,如果当前是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto,wmNews,materials);


        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }
    //1 如果当前封面类型为自动，设置封面图片类型数据
    //如果内容图片大于等一小于三  单图type1
    //如果内容图片大于三  单图type3
    //如果内容没有图片  单图type0
    //图片与素材的关系
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images=dto.getImages();
//封面类型为自动
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
//        多图
     if (materials.size()>=3){
         wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
         images=materials.stream().limit(3).collect(Collectors.toList());
         //        单图
     } else if (materials.size()>1 && materials.size()<3) {
         wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
         images=materials.stream().limit(1).collect(Collectors.toList());
         //        无图
     }else {
         wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
     }
            //修改文章
            if (images.size()>0 && images!=null){
                wmNews.setImages(StringUtils.join(images,","));
            }
            updateById(wmNews);

    }
    if (images.size()>0 && images!=null){
        saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
    }

    }


    @Autowired
    private WmMaterialMapper materialMapper;
    //处理文章内容的关系
    private void saveRelativeInfoForCONTENT(List<String> materials, Integer id) {
        saveRelativeInfo(materials,id,WemediaConstants.WM_CONTENT_REFERENCE);
    }
        //保存文章图片
    private void saveRelativeInfo(List<String> materials,Integer newsId, Short type) {
    if (materials!=null && !materials.isEmpty()){
        //通过图片的的url查询素材id
        List<WmMaterial> dbMaterials = materialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));

        //判断素材是否有效
        if (dbMaterials!=null && dbMaterials.size()==0){
            //手动抛出异常   数据回滚
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFENCE_FAIL);
        }
        if(materials.size()!=dbMaterials.size()){
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFENCE_FAIL);
        }
        List<Integer> idlist = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());


        wmNewsMaterialMapper.saveRelations(idlist,newsId,type);
    }


    }

    //提取文章图片信息
    private List<String> ectractUrlInfo(String content) {
        List<String> materials=new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")){
                String imUrl = (String) map.get("value");
                materials.add(imUrl);
            }
        }
        return materials;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);


        if (wmNews.getId()==null){
            //保存
            save(wmNews);
        }else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
    }
}
